package cn.sh.yhk.configure.security;

import cn.sh.yhk.model.basic.SMenu;
import cn.sh.yhk.service.basic.UserService;
import cn.sh.yhk.vo.SRoleVo;
import cn.sh.yhk.vo.SUserVo;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IDEA
 * author:Yhk
 * Date:2019/1/9
 * Time:12:08 PM
 */
@Service
public class SecurityUserAuthor implements UserDetailsService {

    @Resource
    private UserService userService;

    /**
     * 授权的时候是对角色授权，而认证的时候应该基于资源，而不是角色，因为资源是不变的，而用户的角色是会变的
     */
    @Override

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SUserVo userVo = userService.securityLogin(username);
        if (null == userVo) {

            throw new UsernameNotFoundException(username);
        }
        List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();

        //List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        for (SRoleVo sRoleVo : userVo.getRoleVoList()) {
            for (SMenu sMenus : sRoleVo.getMenuList()) {
                authorities.add(new SimpleGrantedAuthority(sMenus.getMenuName().toString()));
            }
        }
        AuthorityUtils.createAuthorityList("role_aa");
        MyUserDetails user = new MyUserDetails(userVo.getUserName().toString(), userVo.getPassword(), authorities);
        user.setUserId(userVo.getUserId());
        return user;
    }


}
